import { View, Text, ScrollView, Image, TouchableOpacity, Modal, Dimensions, Animated, PanResponder, Easing, Alert } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import Swiper from 'react-native-swiper';
import { StatusBar } from 'react-native';
import { useEffect, useState, useRef } from 'react';
import ImageView from 'react-native-image-viewing';

const { width: screenWidth } = Dimensions.get('window');

// 商品详情图片
const productImages = [
    require('../../assets/detail/d1.png'),
    require('../../assets/product/s1.png'),
    require('../../assets/detail/d2.png'),
    require('../../assets/detail/d3.png'),
    require('../../assets/detail/d4.png')
];

// 颜色预览图
const colorPreviewImages = {
    '白色': require('../../assets/detail/d1.png'),
    '黑色': require('../../assets/product/s1.png'),
    '卡其': require('../../assets/detail/d2.png'),
    '粉色': require('../../assets/detail/d3.png'),
    '藏青': require('../../assets/detail/d4.png')
};

// 商品规格
const specifications = [
    { id: '1', name: '规格', options: ['S', 'M', 'L', 'XL'] },
    { id: '2', name: '颜色', options: ['白色', '黑色', '卡其', '粉色', '藏青'] },
];

export default function ProductDetail() {
    const insets = useSafeAreaInsets();
    const router = useRouter();
    const [specVisible, setSpecVisible] = useState(false);
    const fadeAnim = useRef(new Animated.Value(0)).current;
    const slideAnim = useRef(new Animated.Value(100)).current;
    const [selectedSpecs, setSelectedSpecs] = useState<Record<string, string>>({
        '1': specifications[0].options[0], // 默认选中第一个尺码
        '2': specifications[1].options[0]  // 默认选中第一个颜色
    });
    const swiperRef = useRef<any>(null);
    const pan = useRef(new Animated.ValueXY()).current;
    const [isImageViewVisible, setIsImageViewVisible] = useState(false);
    const [currentImageIndex, setCurrentImageIndex] = useState(0);
    const [actionType, setActionType] = useState<'cart' | 'buy'>('cart');

    const panResponder = useRef(
        PanResponder.create({
            onStartShouldSetPanResponder: () => true,
            onMoveShouldSetPanResponder: (_, gestureState) => {
                return gestureState.dy > 0;
            },
            onPanResponderMove: (_, gestureState) => {
                if (gestureState.dy > 0) {
                    Animated.event([null, { dy: pan.y }], {
                        useNativeDriver: false,
                    })(_, gestureState);
                }
            },
            onPanResponderRelease: (_, gestureState) => {
                if (gestureState.dy > 50) {
                    hideModal();
                } else {
                    Animated.spring(pan.y, {
                        toValue: 0,
                        useNativeDriver: true,
                        tension: 100,
                        friction: 10,
                    }).start();
                }
            },
        })
    ).current;

    // 获取当前颜色的预览图
    const getCurrentPreviewImage = () => {
        const currentColor = selectedSpecs['2'] || '白色';
        return colorPreviewImages[currentColor as keyof typeof colorPreviewImages];
    };

    // 准备预览图片数据
    const previewImages = Object.values(colorPreviewImages).map(image => ({
        uri: Image.resolveAssetSource(image).uri
    }));

    useEffect(() => {
        StatusBar.setBarStyle('dark-content');
        StatusBar.setBackgroundColor('transparent');
        StatusBar.setTranslucent(true);

        return () => {
            StatusBar.setBarStyle('light-content');
        };
    }, []);

    const handleSpecSelect = (specId: string, option: string) => {
        setSelectedSpecs(prev => ({
            ...prev,
            [specId]: option
        }));
    };

    const showModal = () => {
        setSpecVisible(true);
        pan.setValue({ x: 0, y: 400 });
        Animated.parallel([
            Animated.timing(fadeAnim, {
                toValue: 1,
                duration: 250,
                easing: Easing.out(Easing.ease),
                useNativeDriver: true,
            }),
            Animated.spring(pan.y, {
                toValue: 0,
                useNativeDriver: true,
                tension: 100,
                friction: 10,
            })
        ]).start();
    };

    const hideModal = () => {
        Animated.parallel([
            Animated.timing(fadeAnim, {
                toValue: 0,
                duration: 200,
                easing: Easing.in(Easing.ease),
                useNativeDriver: true,
            }),
            Animated.timing(pan.y, {
                toValue: 400,
                duration: 200,
                easing: Easing.in(Easing.ease),
                useNativeDriver: true,
            })
        ]).start(() => {
            setSpecVisible(false);
            pan.setValue({ x: 0, y: 0 });
        });
    };

    const handleBuyNow = () => {
        setActionType('buy');
        showModal();
    };

    const handleAddToCart = () => {
        setActionType('cart');
        showModal();
    };

    const handleConfirm = () => {
        // 检查是否所有规格都已选择
        const isAllSelected = specifications.every(spec => selectedSpecs[spec.id]);
        if (!isAllSelected) {
            // 这里可以添加提示，提醒用户选择完整规格
            return;
        }

        if (actionType === 'cart') {
            // 处理加入购物车逻辑
            Alert.alert('提示', '已成功加入购物车！');
            hideModal();
        } else {
            // 处理立即购买逻辑
            hideModal();
            router.push({
                pathname: "/product/subOrder",
                params: {
                    size: selectedSpecs['1'],
                    color: selectedSpecs['2'],
                    price: 99,
                    title: 'MLB ENGAOE官方圆领卫衣男女情侣装春季新款宽松休闲重磅内搭上衣'
                }
            } as any);
        }
    };

    // 处理预览图点击
    const handlePreviewImagePress = () => {
        const currentColor = selectedSpecs['2'] || '白色';
        const colorIndex = specifications[1].options.indexOf(currentColor);
        setCurrentImageIndex(colorIndex);
        setIsImageViewVisible(true);
    };

    return (
        <View className="flex-1 bg-gray-50" style={{ paddingTop: insets.top }}>
            {/* 顶部导航栏 */}
            <View
                className="absolute left-0 right-0 z-10 flex-row items-center justify-between px-4"
                style={{ top: insets.top, height: 44 }}
            >
                <TouchableOpacity
                    className="w-8 h-8 items-center justify-center bg-black/20 rounded-full"
                    onPress={() => router.back()}
                >
                    <Ionicons name="chevron-back" size={24} color="#fff" />
                </TouchableOpacity>
                <View className="flex-row gap-4">
                    <TouchableOpacity
                        className="w-8 h-8 items-center justify-center bg-black/20 rounded-full"
                    >
                        <Ionicons name="share-social" size={20} color="#fff" />
                    </TouchableOpacity>
                    <TouchableOpacity
                        className="w-8 h-8 items-center justify-center bg-black/20 rounded-full"
                    >
                        <Ionicons name="heart-outline" size={20} color="#fff" />
                    </TouchableOpacity>
                </View>
            </View>

            <ScrollView className="flex-1" showsVerticalScrollIndicator={false}>
                {/* 商品图片轮播 */}
                <View className="w-full aspect-square">
                    <Swiper
                        ref={swiperRef}
                        loop
                        autoplay
                        autoplayTimeout={2}
                        showsPagination
                        dotStyle={{
                            backgroundColor: 'rgba(255,255,255,0.5)',
                            width: 6,
                            height: 6,
                            borderRadius: 3,
                            marginLeft: 3,
                            marginRight: 3,
                        }}
                        activeDotStyle={{
                            backgroundColor: '#fff',
                            width: 6,
                            height: 6,
                            borderRadius: 3,
                            marginLeft: 3,
                            marginRight: 3,
                        }}
                    >
                        {productImages.map((image, index) => (
                            <Image
                                key={index}
                                source={image}
                                className="w-full h-full"
                                resizeMode="cover"
                            />
                        ))}
                    </Swiper>
                </View>

                {/* 商品信息 */}
                <View className="bg-white px-4 py-4 mt-2">
                    <View className="flex-row items-baseline mb-2">
                        <Text className="text-2xl font-bold text-red-500">¥99</Text>
                        <Text className="text-sm text-gray-400 line-through ml-2">¥199</Text>
                    </View>
                    <Text className="text-lg text-gray-900 leading-6 mb-2">
                        【新品上市】MLB ENGAOE官方圆领卫衣男女情侣装春季新款宽松休闲重磅内搭上衣
                    </Text>
                    <View className="flex-row items-center">
                        <View className="flex-row items-center">
                            <Ionicons name="star" size={14} color="#FFB800" />
                            <Text className="text-sm text-gray-500 ml-1">4.9</Text>
                        </View>
                        <Text className="text-sm text-gray-400 mx-2">|</Text>
                        <Text className="text-sm text-gray-500">月销 2345</Text>
                        <Text className="text-sm text-gray-400 mx-2">|</Text>
                        <Text className="text-sm text-gray-500">好评率 98%</Text>
                    </View>
                </View>

                {/* 商品详情 */}
                <View className="bg-white mt-2 pb-20">
                    <View className="items-center py-4 border-b border-gray-100">
                        <Text className="text-base font-medium text-gray-900">商品详情</Text>
                    </View>
                    <View className="p-4">
                        <Text className="text-base text-gray-700 leading-6 mb-4">
                            产品特点：
                            {'\n'}1. MLB·官方旗舰店
                            {'\n'}2. 优质材质，棉85% 聚酯纤维15%
                            {'\n'}3. 青春流行刺绣毛圈布
                            {'\n'}4. 美式休闲长袖
                        </Text>
                        {productImages.map((image, index) => (
                            <Image
                                key={index}
                                source={image}
                                className="w-full h-96 mb-4"
                                resizeMode="cover"
                            />
                        ))}
                    </View>
                </View>
            </ScrollView>

            {/* 底部操作栏 */}
            <View className="absolute left-0 right-0 bottom-0 flex-row items-center bg-white border-t border-gray-100 px-4 pb-6 pt-2">
                <View className="flex-row items-center gap-4 mr-4">
                    <TouchableOpacity className="items-center" activeOpacity={0.7}>
                        <Ionicons name="chatbubble-outline" size={24} color="#666" />
                        <Text className="text-xs text-gray-500 mt-1">客服</Text>
                    </TouchableOpacity>
                    <TouchableOpacity className="items-center" activeOpacity={0.7}>
                        <Ionicons name="cart-outline" size={24} color="#666" />
                        <Text className="text-xs text-gray-500 mt-1">购物车</Text>
                    </TouchableOpacity>
                </View>
                <View className="flex-1 flex-row gap-2">
                    <TouchableOpacity
                        className="flex-1 h-11 items-center justify-center bg-orange-500 rounded-full"
                        activeOpacity={0.7}
                        onPress={handleAddToCart}
                    >
                        <Text className="text-white font-medium">加入购物车</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        className="flex-1 h-11 items-center justify-center bg-red-500 rounded-full"
                        activeOpacity={0.7}
                        onPress={handleBuyNow}
                    >
                        <Text className="text-white font-medium">立即购买</Text>
                    </TouchableOpacity>
                </View>
            </View>

            {/* 规格选择弹窗 */}
            <Modal
                visible={specVisible}
                transparent
                animationType="none"
                onRequestClose={hideModal}
                statusBarTranslucent
            >
                <TouchableOpacity
                    activeOpacity={1}
                    onPress={hideModal}
                    className="flex-1"
                >
                    <Animated.View
                        className="flex-1 bg-black/50 justify-end"
                        style={{
                            opacity: fadeAnim,
                        }}
                    >
                        <TouchableOpacity activeOpacity={1}>
                            <Animated.View
                                className="bg-white rounded-t-3xl"
                                style={{
                                    transform: [{ translateY: pan.y }],
                                }}
                                {...panResponder.panHandlers}
                            >
                                {/* 下滑指示器 */}
                                <View className="w-full items-center pt-2 pb-4">
                                    <View className="w-10 h-1 rounded-full bg-gray-200" />
                                </View>

                                <View className="p-4 border-b border-gray-100">
                                    <View className="flex-row">
                                        <TouchableOpacity
                                            activeOpacity={0.9}
                                            onPress={handlePreviewImagePress}
                                        >
                                            <Image
                                                source={getCurrentPreviewImage()}
                                                className="w-24 h-24 rounded-lg"
                                                resizeMode="cover"
                                            />
                                        </TouchableOpacity>
                                        <View className="ml-3 flex-1">
                                            <Text className="text-lg font-bold text-red-500">¥99</Text>
                                            <Text className="text-sm text-gray-500 mt-1">
                                                已选：
                                                {Object.entries(selectedSpecs).map(([id, value]) => {
                                                    const spec = specifications.find(s => s.id === id);
                                                    return spec ? `${spec.name}:${value} ` : '';
                                                })}
                                            </Text>
                                        </View>
                                        <TouchableOpacity
                                            className="w-8 h-8 items-center justify-center"
                                            onPress={hideModal}
                                        >
                                            <Ionicons name="close" size={24} color="#666" />
                                        </TouchableOpacity>
                                    </View>
                                </View>

                                <ScrollView className="max-h-96 px-4">
                                    {specifications.map((spec) => (
                                        <View key={spec.id} className="py-4 border-b border-gray-100">
                                            <Text className="text-gray-500 mb-3">{spec.name}</Text>
                                            <View className="flex-row flex-wrap gap-2">
                                                {spec.options.map((option, index) => (
                                                    <TouchableOpacity
                                                        key={index}
                                                        className={`px-4 py-2 border rounded-full ${selectedSpecs[spec.id] === option
                                                                ? 'border-red-500 bg-red-50'
                                                                : 'border-gray-200'
                                                            }`}
                                                        activeOpacity={0.7}
                                                        onPress={() => handleSpecSelect(spec.id, option)}
                                                    >
                                                        <Text
                                                            className={`text-sm ${selectedSpecs[spec.id] === option
                                                                    ? 'text-red-500'
                                                                    : 'text-gray-800'
                                                                }`}
                                                        >
                                                            {option}
                                                        </Text>
                                                    </TouchableOpacity>
                                                ))}
                                            </View>
                                        </View>
                                    ))}
                                </ScrollView>

                                <View className="p-4">
                                    <TouchableOpacity
                                        className="w-full h-12 bg-red-500 rounded-full items-center justify-center"
                                        activeOpacity={0.7}
                                        onPress={handleConfirm}
                                    >
                                        <Text className="text-white font-medium">确定</Text>
                                    </TouchableOpacity>
                                </View>
                            </Animated.View>
                        </TouchableOpacity>
                    </Animated.View>
                </TouchableOpacity>
            </Modal>

            {/* 图片预览组件 */}
            <ImageView
                images={previewImages}
                imageIndex={currentImageIndex}
                visible={isImageViewVisible}
                onRequestClose={() => setIsImageViewVisible(false)}
                swipeToCloseEnabled={true}
                doubleTapToZoomEnabled={true}
                presentationStyle="overFullScreen"
            />
        </View>
    );
}